﻿/// <reference path="Alert.js" />
$(function () {
    var GetExperiencia = function () {
        var experiencia = new Experiencia();
        experiencia.Empresa = $("input[id$='Empresa']").val();
        //$("input[id$='NomeCargoExperiencia']").val();
        experiencia.ExperienciaId = parseInt($("input[id$='ExperienciaId']").val(), 10);
        experiencia.ExperienciaId = isNaN(experiencia.ExperienciaId) ? 0 : experiencia.ExperienciaId;
        experiencia.CargoId = parseInt($("input[id$='CargoExperienciaId']").val(), 10);
        dateParts = $("input[id$='DataInicio']").val().split("/");
        experiencia.DataAdmissao = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
        dateParts = $("input[id$='DataFim']").val().split("/");
        experiencia.DataDemissao = new Date(dateParts[2], (dateParts[1] - 1), dateParts[0]);
        experiencia.NomeContato = $("input[id$='NomeContatoExperiencia']").val();
        experiencia.TelefoneEmpresa = $("input[id$='TelefoneContatoExperiencia']").val();
        experiencia.CurriculoId = parseInt($("input[id$='CurriculoId']").val(), 10);
        experiencia.CurriculoId = isNaN(experiencia.CurriculoId) ? 0 : experiencia.CurriculoId;
        experiencia.Atividades = $("textarea[id$='Atividades']").val();
        experiencia.EmpregoAtual = $("input[id$='EmpregoAtual']").is(":checked");
        return experiencia;
    }
    $("input[id$='EmpregoAtual']").change(function () {
        if ($(this).is(":checked") == true) {
            $("input[id$='DataFim']").attr("disabled", true);
        } else {
            $("input[id$='DataFim']").attr("disabled", false);
        }
    });
    $("input[id$='btnAdionaExperiencia']").click(function (e) {
        e.preventDefault();
        var _alert = new Alert();
        _alert.Type = AlertType.Error;
        _alert.Name = "erroGeral";
        try {
            var experiencia = new GetExperiencia();
            if (experiencia.Empresa == undefined || experiencia.Empresa == null || experiencia.Empresa.length == "") {
                _alert.AddMessage("Empresa inválida");
            }
            if (experiencia.CargoId == undefined || isNaN(experiencia.CargoId) || experiencia.CargoId == 0) {
                _alert.AddMessage("Cargo inválido");
            }
            if (experiencia.CurriculoId == undefined || isNaN(experiencia.CurriculoId) || experiencia.CurriculoId == 0) {
                _alert.AddMessage("Curriculo inválido inválido");
            }
            if (experiencia.DataAdmissao == undefined || isNaN(experiencia.DataAdmissao) || experiencia.DataAdmissao == null) {
                _alert.AddMessage("Data início inválida");
            }
            if (experiencia.EmpregoAtual == false && (experiencia.DataDemissao == undefined || isNaN(experiencia.DataDemissao) || experiencia.DataDemissao == null)) {
                _alert.AddMessage("Data fim inválida");
            }
            if (experiencia.EmpregoAtual == true && (experiencia.DataDemissao != undefined && !isNaN(experiencia.DataDemissao) && experiencia.DataDemissao != null)) {
                _alert.AddMessage("Data fim inválida, você marcou esta experiencia como sendo sua atividade atual, neste caso não preencha o campo de data fim");
            }
            if (_alert.HasMessage()) {
                _alert.Show();
                return;
            }
            //            experiencia.DataAdmissao = experiencia.DataAdmissao.toUTCString();
            //            experiencia.DataDemissao = experiencia.DataDemissao.toUTCString();
            experiencia.Salvar();
        } catch (e) {

        }
        return false;
    });
});

function Experiencia() {
    this.ExperienciaId = 0;
    this.CurriculoId = 0;
    this.Empresa = "";
    this.CargoId = 0;
    this.Atividades = "";
    this.DataAdmissao = new Date();
    this.DataDemissao = new Date();
    this.EmpregoAtual = false;
    this.NomeContato = "";
    this.TelefoneEmpresa = "";

    this.Excluir = function (callback) {
        __post("Views/Cadastros/Curriculo.aspx/RemoveExperiencia", "{ 'experienciaId': " + this.ExperienciaId.toString(10) + "}", function (e) {
            callback.call(this, { status: "success", retorno: e });
        }, function () {
            callback.call(this, { status: "error", retorno: e });
        });
    }

    this.Salvar = function () {
        var dtAdmissaoO = this.DataAdmissao;
        var dtDemissaoO = this.DataDemissao;
        this.DataAdmissao = this.DataAdmissao.toJSON()
        if (this.DataDemissao != undefined && !isNaN(this.DataDemissao) && this.DataAdmissao != null)
            this.DataDemissao = this.DataDemissao.toJSON();
        //this.DataDemissao = new Date("0001", "01", "01");
        var json = JSON.stringify(this);
        this.DataAdmissao = dtAdmissaoO;
        this.DataDemissao = dtDemissaoO;
        current = this;

        __post("Views/Cadastros/Curriculo.aspx/AddExperiencia", '{ "experiencia" : ' + json + '}', function (e) {

            var tbody = "<tr experiencia='" + current.ExperienciaId + "'><td>" + $("input[id$='Empresa']").val() + "</td><td>" + $("input[id$='NomeCargoExperiencia']").val() +
                        "</td><td>" + getDateString(current.DataAdmissao) + "</td><td>" + getDateString(current.DataDemissao) + "</td><td><input type='button' id='btnRemoveExperiencia'" + current.ExperienciaId.toString(10) +
                         " onclick='RemoveExperiencia(" + current.ExperienciaId + ", this)' class='btn btn-danger' value='remover'/></td></tr>";
            $('table[id$="gridExperiencia"] tr:last').after(tbody);
            $("input[id$='Empresa']").val("");
            $("input[id$='NomeCargoExperiencia']").val("");
            $("input[id$='ExperienciaId']").val("");
            $("input[id$='CargoExperienciaId']").val("");
            $("input[id$='DataInicio']").val("");
            $("input[id$='DataFim']").val("");
            $("input[id$='NomeContatoExperiencia']").val("");
            $("input[id$='TelefoneContatoExperiencia']").val("");
            $("input[id$='Atividades']").val("");
            $("input[id$='EmpregoAtual']").removeAttr("checked");
            $("input[id$='DataFim']").attr("enable", true);
        });
    }

    var getDateString = function (date) {
        if (date == undefined || isNaN(date) || date == null)
            return "";
        return (date.getDay() < 10 ? "0" + date.getDay() : date.getDay()) + "/" +
               (date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth()) + "/" +
                date.getFullYear();
    }

    var __post = function (url, parans, success, error) {
        var alerta = new Alert();
        alerta.Type = AlertType.Error;
        alerta.Name = "erroGeral";
        $.ajax({
            url: eS.UrlPadrao + url,
            type: "post",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            data: parans,
            success: function (e) {
                if (e.d && e.d.AlertType != undefined) {
                    alerta.Type = e.d.AlertType;
                    for (var i in e.d.Messages) {
                        alerta.AddMessage(e.d.Messages[i]);
                    }
                    if (e.d.Show && e.d.Show == true) {
                        alerta.Show();
                    }
                } else {
                    if (e.responseText) {
                        alerta.Type = 2;
                        alerta.AddMessage(e.responseText);
                    } else {
                        alerta.Type = 1;
                        alerta.AddMessage("Retorno inválido, o objeto retornado não está em um formato correto")
                    }
                    alerta.Show();
                }
                if (alerta.Type == AlertType.Success && success && typeof success == "function") {
                    success.call(this, e);
                }
            },
            error: function (e) {
                alerta.Type = 1;
                alerta.AddMessage(e.responseText);
                alerta.Show();
                if (error && typeof error == "function") {
                    error.call(this, e);
                }
            }
        });
    }
    return this;
}

function RemoveExperiencia(experienciaId, target) {
    var experiencia = new Experiencia();
    experiencia.ExperienciaId = experienciaId && !isNaN(experienciaId) ? experienciaId : 0;
    experiencia.Excluir(function (e) {        
        if (e.status == "success") {
            $(target).parent().parent().remove();
        }
    });
}